/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component,Fragment} from 'react';
import {Form, Input, Radio, Select, Checkbox, Button,message  } from 'antd';
import request from '@/utils/request';
import groupBy from 'lodash/groupBy';
import forEach from 'lodash/forEach';
import { connect } from 'dva';
const FormItem = Form.Item;
const { TextArea } = Input;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.groupMap={
      账号角色:"账号角色",
      集中器管理:"集中器管理",
    }
    this.state = {
      group:{}
    };
  }
  componentDidMount() {
    const that=this;
    request(`/all_permissions`, {
      method: 'GET',
    }).then((response)=> {
      console.log('all_permissions', response)
      if(response.status===200){
        const group = groupBy(response.data.data, 'group')
        console.log('group', group);
        forEach(group, function (value, key) {
          that.setState({
            [key]: value.reduce((result, item)=> {
              console.log('item',item)
              item.label=item.name;
              item.value=item.id;
              result.push({label: item.name, value: item.id})
              return result
            }, [])
          })
          that.setState({
            [key + 'CheckedList']: [],
            [key + 'Indeterminate']: false,
            [key + 'CheckAll']: false,
          })

        });
        that.setState({
          group: group
        }, function () {
          if (this.props.editRecord){
            console.log('修改角色')
            const {permissions}=that.props.editRecord;
            const selectGroup = groupBy(permissions, 'group')
            forEach(selectGroup, function (value, key) {
              that.setState({
                [key + 'CheckedList']: value.reduce((result, item)=> {
                  result.push(item.id)
                  return result
                }, [])
              },function () {
                that.setState({
                  [key + 'Indeterminate']: !!this.state[key + 'CheckedList'].length && (this.state[key + 'CheckedList'].length < this.state[key].length),
                  [key + 'CheckAll']: this.state[key + 'CheckedList'].length === this.state[key].length,
                })
              })
            });

          }
        })
        console.log(this.state)
      }
    })
  }
  onChange2 = (nodes,key) => {
    console.log(nodes)
    console.log(key)
    this.setState({
      [key + 'CheckedList']:nodes,
      [key + 'Indeterminate']: !!nodes.length && (nodes.length < this.state[key].length),
      [key + 'CheckAll']: nodes.length === this.state[key].length,
    })
  }
  onCheckAllChange2 = (e,key) => {
    this.setState({
      [key + 'CheckedList']: e.target.checked ? this.state[key].map((item, index)=> {
        return item.value
      }) : [],
      [key + 'Indeterminate']: false,
      [key + 'CheckAll']: e.target.checked,
    });
  }
  renderXheckGroup = (group)=> {
    const that = this
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: {span: 24},
        sm: {offset: 3, span: 20},
      }
    }
    let result = []
    forEach(group, function (value, key) {
      console.log('key',key)
      result.push((
        <FormItem
          className={'custom-checkgroup'}
          key={key}
          {...formItemLayoutWithOutLabel}
        >
          <div className="checkgroup-title">
            <Checkbox
              indeterminate={that.state[key + 'Indeterminate']}
              onChange={(e)=>that.onCheckAllChange2(e,key)}
              checked={that.state[key + 'CheckAll']}
            >
              {key}
            </Checkbox>
          </div>
          <CheckboxGroup options={that.state[key]} value={that.state[key + 'CheckedList']} onChange={(node)=>that.onChange2(node,key)}/>
        </FormItem>
      ))
    });

    return result
  }
  handleSubmit2 = (e)=> {
    e.preventDefault();
    const that = this;
    const id =  this.props.editRecord&&this.props.editRecord.id;
    this.props.form.validateFields({force: true},
      (err, values) => {
        if (!err) {
          console.log(values)
          const type = !this.props.editRecord ? 'roles/add' : 'roles/edit';
          const msg = !this.props.editRecord ? '添加角色成功' : '修改角色成功';
          const permissions=[];
          forEach(that.state.group, function (value, key) {
            permissions.push(...that.state[key + 'CheckedList'])
          });
          // console.log('permissions',permissions)
          const data =!this.props.editRecord ? {
            permission_ids: permissions,
            ...values
          } : {
            id,
            permission_ids: permissions,
            ...values
          };
          this.props.dispatch({
            type: type,
            payload:data,
            callback: function () {
              message.success(msg);
              that.props.onSave()
            }
          });
        }
      }
    );
  }
  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15},
      }
    };

    const {getFieldDecorator} = this.props.form;
    return (
      <div>
        <Form onSubmit={this.handleSubmit} style={{paddingBottom:'20px'}}>
          {
            !this.props.hiddenSave&&
            <Fragment>
              <h2 style={{textAlign:'center'}}>基本信息</h2>
              <FormItem
                {...formItemLayoutWithLabel}
                label={(
                  <span>
               角色名称
            </span>
                )}
              >
                {getFieldDecorator('name', {
                  initialValue: this.props.editRecord ? this.props.editRecord.name : '',
                  rules: [{ required: true, message: '请输入名称' }],
                })(
                  <Input disabled={Boolean(this.props.editRecord)&&this.props.editRecord.name==='超级管理员'}/>
                )}
              </FormItem>
              <FormItem
                {...formItemLayoutWithLabel}
                label={(
                  <span>
               描述
            </span>
                )}
              >
                {getFieldDecorator('description', {
                  initialValue: this.props.editRecord ? this.props.editRecord.description : '',
                })(
                  <Input />
                )}
              </FormItem>
            </Fragment>
          }

          <h2 style={{textAlign:'center'}}>权限信息</h2>
          {this.renderXheckGroup(this.state.group)}
        </Form>
        {
          !this.props.hiddenSave&&
          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button onClick={this.props.onClose} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={this.handleSubmit2} type="primary">
              确定
            </Button>
          </div>
        }

      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


